﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.ServiceProcess;

namespace SmtpTestServer
{
    [RunInstaller(true)]
    public partial class SmtpTestServerInstaller : System.Configuration.Install.Installer
    {
        public SmtpTestServerInstaller()
        {
            InitializeComponent();

            _processInstaller = new ServiceProcessInstaller();
			_serviceInstaller = new ServiceInstaller();

			_processInstaller.Account = ServiceAccount.LocalSystem;
			_serviceInstaller.StartType = ServiceStartMode.Automatic;
			_serviceInstaller.ServiceName = "SmtpTestServer";
			_serviceInstaller.Description = "Smtp Test Service";
			_serviceInstaller.DisplayName = "SmtpTestServer";

			Installers.Add(_serviceInstaller);
			Installers.Add(_processInstaller);
        }

        private readonly ServiceProcessInstaller _processInstaller;

		private readonly ServiceInstaller _serviceInstaller;

    
		public override void Install(IDictionary stateSaver)
		{
			base.Install(stateSaver);
			ServiceController controller = new ServiceController("SmtpTestServer Controller");
			try
			{
				controller.Start();
			}
			catch (Exception ex)
			{
				string source = "SmtpTestServer";
				string log = "Application";
				if (!EventLog.SourceExists(source))
				{
					EventLog.CreateEventSource(source, log);
				}

				EventLog eventLog = new EventLog();
				eventLog.Source = source;
				eventLog.WriteEntry(string.Format(@"The service could not be started. Please start the service manually. Error: {0}", ex.Message), EventLogEntryType.Error);
			}
		}
    }
}
